package com.beta.cat.config.dubbo2;

import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.common.Parameters;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.remoting.ChannelHandler;
import org.apache.dubbo.remoting.RemotingException;
import org.apache.dubbo.remoting.exchange.ExchangeClient;
import org.apache.dubbo.remoting.exchange.ExchangeHandler;

import java.net.InetSocketAddress;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.atomic.AtomicInteger;

import static org.apache.dubbo.remoting.Constants.SEND_RECONNECT_KEY;
import static org.apache.dubbo.rpc.protocol.dubbo.Constants.LAZY_CONNECT_INITIAL_STATE_KEY;

/**
 * 主要是因为原来的源码中，这个类不是public，无法被外部引用，所以创建了这个类。<br>
 * 这个类中最主要的就是改了close方法中的内容
 */
@Slf4j
public class ReferenceCountExchangeClient2 implements ExchangeClient {

    private final URL url;
    private final AtomicInteger referenceCount = new AtomicInteger(0);
    private final AtomicInteger disconnectCount = new AtomicInteger(0);
    private final Integer maxDisconnectCount = 50;
    private ExchangeClient client;

    public ReferenceCountExchangeClient2(ExchangeClient client) {
        this.client = client;
        referenceCount.incrementAndGet();
        this.url = client.getUrl();
    }

    @Override
    public void reset(URL url) {
        client.reset(url);
    }

    @Override
    public CompletableFuture<Object> request(Object request) throws RemotingException {
        try {
            return client.request(request);
        } catch (RemotingException e) {
            close();
            return client.request(request);
        }
    }

    @Override
    public URL getUrl() {
        return client.getUrl();
    }

    @Override
    public InetSocketAddress getRemoteAddress() {
        return client.getRemoteAddress();
    }

    @Override
    public ChannelHandler getChannelHandler() {
        return client.getChannelHandler();
    }

    @Override
    public CompletableFuture<Object> request(Object request, int timeout) throws RemotingException {
        try {
            return client.request(request, timeout);
        } catch (RemotingException e) {
            close();
            return client.request(request, timeout);
        }
    }

    @Override
    public CompletableFuture<Object> request(Object request, ExecutorService executor) throws RemotingException {
        try {
            return client.request(request, executor);
        } catch (RemotingException e) {
            close();
            return client.request(request, executor);
        }
    }

    @Override
    public CompletableFuture<Object> request(Object request, int timeout, ExecutorService executor) throws RemotingException {
        try {
            return client.request(request, timeout, executor);
        } catch (RemotingException e) {
            close();
            return client.request(request, timeout, executor);
        }
    }

    @Override
    public boolean isConnected() {
        return client.isConnected();
    }

    @Override
    public void reconnect() throws RemotingException {
        try {
            client.reconnect();
        } catch (RemotingException e) {
            close();
            client.reconnect();
        }
    }

    @Override
    public InetSocketAddress getLocalAddress() {
        return client.getLocalAddress();
    }

    @Override
    public boolean hasAttribute(String key) {
        return client.hasAttribute(key);
    }

    @Override
    public void reset(Parameters parameters) {
        client.reset(parameters);
    }

    @Override
    public void send(Object message) throws RemotingException {
        try {
            client.send(message);
        } catch (RemotingException e) {
            close();
            client.send(message);
        }
    }

    @Override
    public ExchangeHandler getExchangeHandler() {
        return client.getExchangeHandler();
    }

    @Override
    public Object getAttribute(String key) {
        return client.getAttribute(key);
    }

    @Override
    public void send(Object message, boolean sent) throws RemotingException {
        try {
            client.send(message, sent);
        } catch (RemotingException e) {
            close();
            client.send(message, sent);
        }
    }

    @Override
    public void setAttribute(String key, Object value) {
        client.setAttribute(key, value);
    }

    @Override
    public void removeAttribute(String key) {
        client.removeAttribute(key);
    }

    /**
     * close() is not idempotent any longer
     */
    @Override
    public void close() {
        close(0);
    }

    @Override
    public void close(int timeout) {
        //只要有服务的provider下线，就强制关闭一下，反正心跳检测那边会有重新建立连接的情况
        if (referenceCount.decrementAndGet() <= 1) {
            try {
                log.debug("close >>" + client.getUrl());
                if (timeout == 0) {
                    client.close();
                } else {
                    client.close(timeout);
                }
                replaceWithLazyClient();
            } catch (Exception e) {
                log.info(e.getMessage(), e);
            }
        }
    }

    @Override
    public void startClose() {
        client.startClose();
    }

    /**
     * when closing the client, the client needs to be set to LazyConnectExchangeClient, and if a new call is made,
     * the client will "resurrect".
     *
     * @return
     */
    private void replaceWithLazyClient() {
        // this is a defensive operation to avoid client is closed by accident, the initial state of the client is false
        URL lazyUrl = url.addParameter(LAZY_CONNECT_INITIAL_STATE_KEY, Boolean.TRUE)
                //.addParameter(RECONNECT_KEY, Boolean.FALSE)
                .addParameter(SEND_RECONNECT_KEY, Boolean.TRUE.toString());
        //.addParameter(LazyConnectExchangeClient.REQUEST_WITH_WARNING_KEY, true);

        if (disconnectCount.getAndIncrement() % maxDisconnectCount == 0) {
            log.warn(url.getAddress() + " " + url.getServiceKey() + " safe guard client , should not be called ,must have a bug.");
        }

        /**
         * the order of judgment in the if statement cannot be changed.
         */
        if (!(client instanceof LazyConnectExchangeClient2) || client.isClosed()) {
            client = new LazyConnectExchangeClient2(lazyUrl, client.getExchangeHandler());
//            log.info("这里本来通过创建LazyConnectExchangeClient2的方式保留旧连接:{}！", getUrl());
        }
    }

    @Override
    public boolean isClosed() {
        return client.isClosed();
    }

    /**
     * The reference count of current ExchangeClient, connection will be closed if all invokers destroyed.
     */
    public void incrementAndGetCount() {
        referenceCount.incrementAndGet();
    }

    public int getCount() {
        return referenceCount.get();
    }

    public String toString() {
        return "referenceCount:" + referenceCount + ", url:" + (url == null ? null : url.toString());
    }
}

